package com.okilo.online.app.request

import android.os.Handler
import android.os.Looper
import com.okilo.online.app.configs.OkiloConfigs.addParams
import com.okilo.online.app.configs.OkiloConfigs
import com.okilo.online.app.event.room.OkiloPointManager
import com.okilo.online.app.tools.aes.OkiloAesUtil
import com.okilo.online.app.tools.log.OkiloLog
import com.okilo.online.app.tools.log.JsonFormat
import org.json.JSONObject
import java.io.IOException


/**
 * HttpLoader
 * @Author wwdeng
 * @CreateTime: 2024/11/20 17:38
 * @Annotation：网络请求
 */
class HttpLoader: IHttpLoader {
    private val mainHandler = Handler(Looper.getMainLooper())
    /**
     * post 请求
     */
    override fun post(url: String, params: JSONObject,callback: IHttpCallback) {
        //统一添加通用参数
        params.addParams()
        val aesParams = OkiloAesUtil.encryptDefault(params.toString())
        OkiloLog.i("HttpUrl：  $url")
        OkiloLog.i("HttpParams： $params")
        OkiloLog.i("HttpParams AES：  $aesParams")

        val headers = HashMap<String,String>()
        headers["appid"] = OkiloConfigs.OKILO_APPNAME
        headers["product"] = OkiloConfigs.OKILO_APPNAME
        OkHttpUtil.getInstance().postJson(url, aesParams,headers,object: OkHttpUtil.HttpCallback {
            override fun onSuccess(response: String) {
                mainHandler.post {
                    callback.onRequestFinish()
                }
                response.let {
                    val result = OkiloAesUtil.decryptDefault(it)
                    Thread {
                        OkiloLog.i(
                            "\nurl: $url \n" +
                                    "path: ${params.optString("path")} \n" +
                                    "response: ${JsonFormat.format(result)}"
                        )
                    }.start()

                    val data = JSONObject(result)
                    when(val code = data.optInt("code")){
                        0 -> {
                            mainHandler.post { callback.onRequestSuccess(data) }
                        }

                        else -> {
                            val errorObj = JSONObject()
                            errorObj.put("errorCode",code)
                            errorObj.put("errorMsg",data.optString("msg"))
                            mainHandler.post {
                                callback.onRequestError(errorObj)
                            }
                        }
                    }
                }
            }

            override fun onFailure(e: IOException) {
                OkiloLog.i(
                    "\nurl: $url \n" +
                            "path: ${params.optString("path")} \n" +
                            "error: ${e?.message}"
                )
                val errorObj = JSONObject()
                errorObj.put("errorCode",-1)
                errorObj.put("errorMsg",e?.message)
                mainHandler.post {
                    callback.onRequestError(errorObj)
                    callback.onRequestFinish()
                }
            }
        })
    }

    /**
     * 文件上传
     */
    override fun upload(filePath: String, callback: IHttpCallback) {
        if (filePath.isEmpty()){
            return
        }
        val headers = HashMap<String,String>()
        headers["appid"] = OkiloConfigs.OKILO_APPNAME
        headers["product"] = OkiloConfigs.OKILO_APPNAME

        val httpUrl = OkiloConfigs.gOkiloUploadFileUrl()
        OkHttpUtil.getInstance()
            .uploadFile(httpUrl, "image", filePath,null,headers,object: OkHttpUtil.HttpCallback {
            override fun onSuccess(response: String) {
                mainHandler.post {
                    callback.onRequestFinish()
                }
                response.let {
                    Thread {
                        OkiloLog.i(
                            "\nurl: $httpUrl \n" +
                                    "imgPath: $filePath \n" +
                                    "response: ${JsonFormat.format(it)}"
                        )
                    }.start()

                    val data = JSONObject(it)
                    when(val code = data.optInt("code")){
                        0 -> {
                            mainHandler.post { callback.onRequestSuccess(data) }
                        }

                        else -> {
                            val errorObj = JSONObject()
                            errorObj.put("errorCode",code)
                            errorObj.put("errorMsg",data.optString("msg"))
                            mainHandler.post {
                                callback.onRequestError(errorObj)
                            }
                        }
                    }
                }
            }

            override fun onFailure(e: IOException) {
                OkiloLog.i(
                    "\nurl: $httpUrl \n" +
                            "imgPath: $filePath \n" +
                            "error: ${e.message}"
                )
                val errorObj = JSONObject()
                errorObj.put("errorCode",-1)
                errorObj.put("errorMsg",e?.message)
                mainHandler.post {
                    callback.onRequestError(errorObj)
                    callback.onRequestFinish()
                }
            }
        })
    }

    /**
     * 添加打点事件
     */
    override fun addPoint(eventName: String, remark: String?) {
        OkiloLog.i(">>>>>>>>>>>>>>eventName：$eventName，remark：$remark")
        val eventType = eventName.uppercase()//转大写
        if (remark != null){
            OkiloPointManager.getInstance().track(eventType,remark)
        } else {
            OkiloPointManager.getInstance().track(eventType,"")
        }
    }

    /**
     * 设置请求tag
     */
    override fun setTag(tag: Any) {
    }

    /**
     * 取消请求
     */
    override fun cancelTag(tag: Any) {
    }
}